<?php 
	session_start();
	header("Content-type:text/html;charset=utf-8");

	$id = $_GET['id'];
	$user_name = $_SESSION['user_name'];

	$conn = 	$conn = mysqli_connect('127.0.0.1','root','pwd','admin',3306);
	mysqli_set_charset($conn,'utf8');

	$sql_select="select title,price,num from juice where id= '{$id}'";
	$stmt=mysqli_prepare($conn,$sql_select); 
	//mysqli_stmt_bind_param($stmt,'s',$productid);
	mysqli_stmt_execute($stmt);
	$result=mysqli_stmt_get_result($stmt);
	$row=mysqli_fetch_assoc($result);

	$title = $row['title'];
	$price = $row['price'];
	$num = $row['num'];


	mysqli_close($conn);

	$conn1 = 	$conn = mysqli_connect('127.0.0.1','root','pwd','admin',3306);

	$sql = "CREATE TABLE  IF NOT EXISTS $user_name (
	id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
	productid VARCHAR(30) NOT NULL,
	title VARCHAR(30) NOT NULL,
	price VARCHAR(30) NOT NULL,
	num VARCHAR(30) NOT NULL
	)";

	if ($conn1->query($sql) === FALSE) {
	    echo "创建数据表错误: " . $conn1->error;
	}

		$sql_select2 = "select productid from $user_name";
		$stmt2=mysqli_query($conn1,$sql_select2);
		$cunzai = false;
		while ($row2=mysqli_fetch_assoc($stmt2)) {
			if ($id == $row2['productid']) {
				$cunzai = true;
			}
		}
		if ($cunzai) {
			if( mysqli_query($conn1,"UPDATE $user_name SET num=num +'{$num}' WHERE productid='{$id}'")){
				echo "<script>alert('再次加入购物车成功');location='juice_order.php'</script>";
			}else{
				echo "<script>alert('再次加入购物车失败');location='juice_order.php'</script>";
			}
		}else{
			$sql_insert = "INSERT INTO $user_name (productid,title,price,num) VALUES ('$id', '$title', '$price','$num')";
			if (mysqli_query($conn1, $sql_insert)) {
    			echo "<script>alert('首次加入购物车成功');location='juice_order.php'</script>";
			} else {
   				echo "<script>alert('首次加入购物车失败');location='juice_order.php'</script>";
			}
		}
?>